package br.academia.dominio;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@SuppressWarnings("serial")
@Entity
@Table(name="usuario", schema="public", uniqueConstraints={@UniqueConstraint(columnNames={"login"})})
public class Usuario extends PersistDB{
	@Id
	@Column(name="id_usuario")
	@SequenceGenerator(allocationSize=1, name = "SEQ_ID_USUARIO", sequenceName = "public.seq_id_usuario")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_ID_USUARIO")
	private int id;
	
	@Column(length=128)
	private String login;
	
	@Column(length=64)
	private String senha;
	
	public Usuario(){
		
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getSenha() {
		return senha;
	}

	public void setMD5Senha(String senhaMD5){
		this.senha = senhaMD5;
	}
	
	public void setSenha(String senha) {
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		md.update(senha.getBytes());
		byte[] hashMd5 = md.digest();

		StringBuilder novaSenha = new StringBuilder();
		
		for (int i = 0; i < hashMd5.length; i++) {
			int parteAlta = ((hashMd5[i] >> 4) & 0xf) << 4;
			int parteBaixa = hashMd5[i] & 0xf;
			if (parteAlta == 0) novaSenha.append('0');
			novaSenha.append(Integer.toHexString(parteAlta | parteBaixa));
		}
		
		this.senha = novaSenha.toString();
	}
}
